package guoan.service;

import guoan.core.common.WebConfig;
import guoan.core.dto.RestResponse;
import guoan.domain.RandomKey;
import guoan.domain.Student;
import guoan.repository.RandomKeyRepository;
import guoan.repository.StudentRepository;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

@Service
public class StudentService {
	protected final Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private StudentRepository studentRepository;
	@Autowired
	private RandomKeyRepository randomKeyRepository;

	/**
	 * findOne:根据ID获得学员信息. <br/>
	 *
	 * @author he.sun
	 * @param studentId
	 * @return
	 */
	public Student findOne(Long studentId) {
		// TODO Auto-generated method stub
		return studentRepository.findOne(studentId);
	}

	public Student save(Student student) {
		// TODO Auto-generated method stub
		return studentRepository.save(student);
	}

	public Student findByStudentOpenid(String studentOpenid) {
		// TODO Auto-generated method stub
		return studentRepository.findByStudentOpenid(studentOpenid);
	}

	public RestResponse<Boolean> join(Student student, HttpServletRequest request) {
		// TODO Auto-generated method stub
		Preconditions.checkNotNull(student, "参数错误");

		String key = student.getStudentKey();
		String[] keys = key.split(",");
		List<RandomKey> randomKeys = Lists.newArrayList();
		int coachType = 0;
		for (int i = 0; i < keys.length; i++) {
			RandomKey randomKey = randomKeyRepository.findByKeyAndIsUse(keys[i].toUpperCase(), 0L);
			// 是否存在没有使用过的KEY
			if (randomKey != null) {
				// 科目二科目三不可重复绑定，二或三只能有一个,而且还没有绑定过
				if (randomKey.getCoachType().intValue() != coachType && randomKey.getStudentId() == null) {
					coachType = randomKey.getCoachType().intValue();
					randomKeys.add(randomKey);
				}
			}
		}

		if (randomKeys.size() == 0) {
			return RestResponse.error("您输入的验证码错误，请重新输入");
		}
		// 绑定的时候获取openid 保存在train中
		HttpSession session = request.getSession();
		String openid = (String) session.getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY);
		Student oldStudent = studentRepository.findByStudentOpenid(openid);
		if (oldStudent != null) {
			oldStudent.setStudentName(student.getStudentName());
			oldStudent.setStudentNo(student.getStudentNo());
			oldStudent.setContactNumberF(student.getContactNumberF());
			studentRepository.save(oldStudent);
			for (RandomKey randomKey : randomKeys) {
				if (!oldStudent.getId().equals(randomKey.getStudentId())) {// 不修改原来的key
					if (randomKeyRepository.countByCoachTypeAndStudentId(randomKey.getCoachType(), oldStudent.getId()) == 0) {// 一个科目只可以报名一次
						randomKey.setStudentId(oldStudent.getId());
						randomKey.setIsUse(1L);
						randomKeyRepository.save(randomKey);
					}
				}
			}
		} else {
			student.setStudentOpenid(openid);
			student = studentRepository.save(student);
			for (RandomKey randomKey : randomKeys) {
				if (!student.getId().equals(randomKey.getStudentId())) {// 不修改原来的key
					if (randomKeyRepository.countByCoachTypeAndStudentId(randomKey.getCoachType(), student.getId()) == 0) {// 一个科目只可以报名一次
						randomKey.setStudentId(student.getId());
						randomKey.setIsUse(1L);
						randomKeyRepository.save(randomKey);
					}
				}

			}

		}

		return RestResponse.ok(true);
	}
}
